var express = require('express');
var router = express.Router();
var mongoose = require("../db/connect")
const crypto = require('crypto'); //加密模块 
const jwt = require("jsonwebtoken");
const request = require("request");
var path = require("path")
var fs = require("fs")
const formidable = require('formidable')
var _ = require('underscore');


// const uploadUrl = 'https://xtspace.cn/xcx';
const uploadUrl = 'http://localhost:10048';

var Vuer = mongoose.model("vuer", {
  openid: String,
  userInfo: {
    type: Object,
    default: {
      avatarUrl: "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJ955ibECjtBGklJFibJfMvI8icN3EWY4W4JNhE79rHLwIQ4HvgibXbvA5W8P8He1xT93CZ4DmBZFBQfw/132",
      nickName: "村名"
    }
  },
  confirm: {
    // 发布的
    type: Number,
    default: 0
  },
  aJoin: {
    type: Array,
    default: []
  },
  integral: {
    type: Number,
    default: 0
  },
  name: {
    type: String,
    default: ""
  },
  phone: {
    type: String,
    default: ""
  },
});

var Shuangqiao = mongoose.model("shuangqiao", {
  id: {
    type: String,
    default: 'shuangqiao'
  },
  pwdList: {
    type: Array,
    default: [
      `sqc`,
    ]
  },
});




var Activity = mongoose.model("activity", {
  name: String,
  phone: String,
  type: String,
  createBy: String,
  describe: String,
  site: String,
  duration: Object,
  pic: String,
  integral: Number,
  peoplenum: Number,
  openid: String,
  createTime: Number,
  picture: {
    type: Array,
    default: []
  },
  signup: {
    type: Array,
    default: []
  },
  status: {
    type: Number,
    default: 1
  },
  isSave: {
    // 为true表示发布状态， 否则取消发布
    type: Boolean,
    default: true
  },
  isDone: {
    // 完成状态
    type: Boolean,
    default: false
  }
});

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource of users');
});

router.post('/go-admin', function (req, res, next) {
  // new Shuangqiao().save()
  Shuangqiao.findOne({ id: 'shuangqiao' }).then(response => {
    res.status(200).json({
      code: 200,
      status: 0,
      data: response.pwdList.includes(req.body.pwd),
      message: "yanzheng"
    })
  })
})


router.get('/get-banner', function (req, res, next) {
  // new Shuangqiao().save()
  // Shuangqiao.findOne({ id: req.query.id }).then(response => {
  //   res.status(200).json({
  //     code: 200,
  //     status: 0,
  //     data: response,
  //     message: "get banner 成功"
  //   })
  // })
  Activity.find({}, { __v: 0 }).then(response => {
    let arr = response.filter(item => item.isSave === true && item.isDone === false && item.picture.length > 0);
    arr = arr.map(item => item.picture[0]);
    if (arr.length >= 3) {
      arr = arr.slice(0, 3)
    } else {
      arr = [
        `${uploadUrl}/sys/banner2.png`,
        `${uploadUrl}/sys/banner1.jpeg`,
        `${uploadUrl}/sys/banner3.png`
      ]
    }
    res.status(200).json({
      code: 200,
      status: 0,
      data: arr,
      message: "获取活动成功"
    })
  })
});


//登录
router.post("/login", (req, res) => {
  var { code, userInfo } = req.body;
  var id = 'wxd3aba020bbe8fa8b';  //appid
  var secret = 'd64223c8df23ab86800b11d7eef0e781'; //appsecret
  var url = `https://api.weixin.qq.com/sns/jscode2session?appid=${id}&secret=${secret}&js_code=${code}&grant_type=authorization_code`
  request.get(url, (err, response, body) => {
    var obj = JSON.parse(body);
    // console.log(err, obj)

    if (obj.errcode || err) {
      res.json({
        code: 201,
        status: 0,
        data: obj,
        message: "错误的code码"
      })
    } else {
      Vuer.findOne({ openid: obj.openid }).then(user => {
        if (user) {
          var token = jwt.sign({ openid: obj.openid, time: Date.now() }, "mp", { expiresIn: 3600 * 12 });
          res.json({
            code: 200,
            status: 0,
            data: {
              login: true,
              openid: obj.openid,
              token
            },
            message: "登录成功"
          })
        } else {
          Vuer.insertMany({ openid: obj.openid, userInfo }).then(result => {
            var token = jwt.sign({ openid: obj.openid, time: Date.now() }, "mp", { expiresIn: 3600 * 12 });
            res.json({
              code: 200,
              status: 0,
              data: {
                login: true,
                openid: obj.openid,
                token
              },
              message: "首次登录成功"
            })
          })
        }
      })
    }
  })
})



// router.use(function (req, res, next) {
//   //验证
//   jwt.verify(req.headers.authorization, "mp", (err, code) => {
//     if (!err) {
//       req.openid = code.openid;
//       next();
//     }
//     else {
//       res.status(401).json({
//         code: 200,
//         status: -1,
//         message: 'error, valid fail'
//       })
//     }
//   })
// })

//得到用户名
router.post('/user-one', (req, res) => {
  Vuer.findOne({ openid: req.body.openid }, { _id: 0, __v: 0 }).then(response => {
    Activity.countDocuments({ openid: req.body.openid }).then((count) => {
      res.status(200).json({
        count: count,
        code: 200,
        status: 0,
        data: response,
        message: '获取用户信息'
      })
    })
  })
})

router.post('/user-many', (req, res) => {
  Vuer.find({}, { _id: 0, __v: 0 }).sort({ integral: -1 }).limit(10).then(response => {
    let obj = {};
    obj.first = response[0] || [];
    obj.second = response[1] || [];
    obj.third = response[2] || [];
    obj.other = response.filter((item, index) => index >= 3) || [];
    // console.log(obj)
    res.status(200).json({
      code: 200,
      status: 0,
      data: obj,
      message: '获取所有用户信息'
    })
  })
})


router.post('/add-act', (req, res) => {
  new Activity({ ...req.body, createTime: new Date().getTime() }).save().then(response => {
    Vuer.findOneAndUpdate({ openid: req.headers.openid }, {
      $inc: {
        confirm: 1
      }
    }).then(() => {
      res.status(200).json({
        code: 200,
        status: 0,
        data: response,
        message: "上传活动成功"
      })
    })
  })
})

router.post('/modify-act', (req, res) => {
  Activity.findOne({ _id: req.body._id }).then(response => {
    _.extend(response, req.body);
    response.save().then(response2 => {
      res.json({
        code: 200,
        status: 0,
        data: response2,
        message: "上传者修改发布"
      })
    })
  })
})

router.post('/cancel-act', (req, res) => {
  Activity.findOneAndUpdate({ _id: req.body.id }, {
    $set: {
      isSave: false,
      status: 3
    }
  }).then(response => {
    res.status(200).json({
      code: 200,
      status: 0,
      data: response,
      message: "上传者取消发布"
    })
  })
})

router.post('/confirm-act', (req, res) => {
  Activity.findOneAndUpdate({ _id: req.body.id, openid: req.headers.openid }, {
    $set: {
      isDone: true,
      status: 2
    }
  }).then(response => {
    // console.log(response)
    if (req.body.arr.length) {
      req.body.arr.forEach((item, index) => {
        Vuer.findOneAndUpdate({ openid: item }, {
          $inc: {
            integral: response.integral
          }
        }).then(() => {
          if (index === (response.signup.length - 1)) {
            res.status(200).json({
              code: 200,
              status: 0,
              data: response,
              message: "上传者完成任务，发放积分"
            })
          }
        })
      })
    } else {
      res.status(200).json({
        code: 200,
        status: 0,
        data: response,
        message: "上传者完成任务，无人获得积分"
      })
    }
  })
})


router.post('/get-act', (req, res) => {
  let obj = {};
  if (req.body.name) {
    obj.name = RegExp(req.body.name)
  }
  Activity.find(obj, { __v: 0 }).then(response => {
    res.status(200).json({
      code: 200,
      status: 0,
      data: response,
      message: "获取活动成功"
    })
  })
})

router.post('/get-act-byid', (req, res) => {
  console.log(typeof (req.body.id), req.body.id)
  let obj = {};
  if (req.body.id) {
    obj._id = req.body.id.trim()
    // 字符串将被强制转换为ObjectId
    // " 5eddfbeb8969bd2a40871b96" //前面有空格
    // "'5eddfbeb8969bd2a40871b96'" //字符串内含引号
    // 不满足(转化)参数条件 12字节的单个字符串或24个十六进制字符的字符串
  }
  Activity.findOne(obj, { __v: 0 }).then(response => {
    let aSign = [];
    if (response.signup.length) {
      aSign = response.signup.filter(item => item.openid === req.headers.openid);
    }
    res.status(200).json({
      code: 200,
      status: 0,
      data: {
        obj: response,
        aSign,// 判断是否已参加
        nums: response.signup.length,
        signup: response.signup
      },
      message: "获取活动成功"
    })
  })
})



router.post('/join-act', (req, res) => {
  const { obj, id } = req.body;
  // console.log(obj, id)
  Activity.findOneAndUpdate({ _id: id }, {
    $addToSet: {
      signup: obj
    }
  }).then(response => {
    Vuer.findOneAndUpdate({ openid: obj.openid }, {
      $addToSet: {
        aJoin: id
        // 1、字符串转ObjectId
        // mongoose.Types.ObjectId(id);
        // 2、ObjectId转字符串
        // mongoose.Types.ObjectId(id).toString()
      }
    }, { new: true }).then(() => {
      res.status(200).json({
        code: 200,
        status: 0,
        data: response,
        message: "参加活动成功"
      })
    })
  })
})

router.post('/quit-act', (req, res) => {
  const { obj, id } = req.body;
  Activity.findOneAndUpdate({ _id: id }, {
    $pull: {
      signup: obj
    }
  }).then(response => {
    Vuer.findOneAndUpdate({ openid: obj.openid }, {
      $pull: {
        aJoin: id
      }
    }).then(() => {
      res.status(200).json({
        code: 200,
        status: 0,
        data: response,
        message: "退出活动成功"
      })
    })
  })
})

router.post('/act-list', (req, res) => {
  Activity.find({ openid: req.headers.openid }, {
    __v: 0
  }).then(response => {
    Vuer.findOne({ openid: req.headers.openid }, {
      __v: 0
    }).then((user) => {
      if (user.aJoin.length) {
        Activity.find({ _id: { $in: user.aJoin } }).then(response2 => {
          res.status(200).json({
            code: 200,
            status: 0,
            create: response,
            join: response2,
            message: "获取分类活动成功"
          })
        })
      } else {
        res.status(200).json({
          code: 200,
          status: 0,
          create: response,
          join: [],
          message: "获取分类活动成功"
        })
      }
    })
  })
})

router.post('/upload', (req, res) => {
  const form = formidable({ multiples: false });
  // const form = new formidable.IncomingForm();
  form.uploadDir = path.join(__dirname, "../public/upload/");
  form.parse(req, (err, fields, files) => {
    if (!files.file) return;  //没有上传文件，不进行任何处理
    //上传文件重命名
    fs.renameSync(files.file.path, form.uploadDir + files.file.name);
    res.status(200).json({
      code: 200,
      status: 0,
      msg: "上传图片成功",
      // result: `https://xtspace.cn/xcx/upload/` + files.file.name
      result: `http://localhost:10048/upload/` + files.file.name
    })
  });
})

module.exports = router;
